package com.huicoo.forestmanager.ui.patrol.forestCampTask.presenter;


import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.ReportEventBean;
import com.huicoo.forestmanager.network.bean.patrol.UploadFileBean;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventBean;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventCommentBean;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.model.ForestCampTaskVerifyEventModel;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.JsonUtils;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.toast.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/8		    Administrator
 * 问题验证
 */
public class ForestCampTaskVerifyEventPresenter implements ForestCampTaskVerifyEventContract.Presenter {
    private ForestCampTaskVerifyEventContract.View view;
    private ForestCampTaskVerifyEventContract.Model model;
    private Thread downloadThread;
    private File file;

    public ForestCampTaskVerifyEventPresenter(ForestCampTaskVerifyEventContract.View view) {
        this.view = view;
        this.model = new ForestCampTaskVerifyEventModel();
    }

    @Override
    public void uploadFile(HashMap<String, String> params, AttachmentEntity attachment) {
        Call<UploadFileBean> call = model.uploadFile(params, attachment);
        call.enqueue(new Callback<UploadFileBean>() {
            @Override
            public void onResponse(@NonNull Call<UploadFileBean> call, @NonNull Response<UploadFileBean> response) {
                try {
                    //数据请求成功
                    LogUtils.v("gogogo upload file result = " + JsonUtils.toJson(response.body()));
                    if (response.body() == null) {
                        //数据请求失败
                        if (view != null) {
                            view.fail("请求结果为空");
                        }
                        return;
                    }
                    if (TextUtils.equals(response.body().getCode(), "200")) {
                        List<UploadFileBean.UploadFileData> Data = response.body().getData();
                        if (Data != null && !Data.isEmpty() && Data.get(0) != null && Data.get(0).IsSuccess) {
                            if (view != null) {
                                view.uploadFileSuccess(Data.get(0), attachment.attachmentType, attachment.during);
                            }
                        } else {
                            if (view != null) {
                                view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                            }
                        }
                    } else {
                        if (view != null) {
                            view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<UploadFileBean> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                LogUtils.v("gogogo on failure = " + t.getMessage());
                if (view != null) {
                    view.fail("请求失败，请重试");
                }
            }
        });
    }

    @Override
    public void replyEvent(HashMap<String, String> params) {
        Call<VerifyEventBean> call = model.replyEvent(params);
        call.enqueue(new Callback<VerifyEventBean>() {
            @Override
            public void onResponse(@NonNull Call<VerifyEventBean> call, @NonNull Response<VerifyEventBean> response) {
                try {
                    //数据请求成功
                    LogUtils.v("gogogo reply event result = " + JsonUtils.toJson(response.body()));
                    if (response.body() == null) {
                        //数据请求失败
                        if (view != null) {
                            view.fail("请求结果为空");
                        }
                        return;
                    }
                    if (TextUtils.equals(response.body().getCode(), "200")) {
                        VerifyEventBean.VerifyEventData Data = response.body().getData();
                        if (Data != null && Data.IsSuccess) {
                            if (view != null) {
                                view.replyEventSuccess();
                            }
                        } else {
                            if (view != null) {
                                view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                            }
                        }
                    } else {
                        if (view != null) {
                            view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<VerifyEventBean> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                if (view != null) {
                    view.fail("请求失败，请重试");
                }
            }
        });
    }

    @Override
    public void verifyEvent(HashMap<String, String> params) {
        Call<VerifyEventBean> call = model.verifyEvent(params);
        call.enqueue(new Callback<VerifyEventBean>() {
            @Override
            public void onResponse(@NonNull Call<VerifyEventBean> call, @NonNull Response<VerifyEventBean> response) {
                try {
                    //数据请求成功
                    LogUtils.v("gogogo verify event result = " + JsonUtils.toJson(response.body()));
                    if (response.body() == null) {
                        //数据请求失败
                        if (view != null) {
                            view.fail("请求结果为空");
                        }
                        return;
                    }
                    if (TextUtils.equals(response.body().getCode(), "200")) {
                        VerifyEventBean.VerifyEventData Data = response.body().getData();
                        if (Data != null && Data.IsSuccess) {
                            if (view != null) {
                                view.verifyEventSuccess();
                            }
                        } else {
                            if (view != null) {
                                view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                            }
                        }
                    } else {
                        if (view != null) {
                            view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<VerifyEventBean> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                if (view != null) {
                    view.fail("请求失败，请重试");
                }
            }
        });
    }

    @Override
    public void getComment(HashMap<String, String> params) {
        Call<VerifyEventCommentBean> call = model.getComment(params);
        call.enqueue(new Callback<VerifyEventCommentBean>() {
            @Override
            public void onResponse(@NonNull Call<VerifyEventCommentBean> call, @NonNull Response<VerifyEventCommentBean> response) {
                try {
                    //数据请求成功
                    LogUtils.v("gogogo get comment result = " + JsonUtils.toJson(response.body()));
                    if (response.body() == null) {
                        //数据请求失败
                        if (view != null) {
                            view.fail("请求结果为空");
                        }
                        return;
                    }
                    if (TextUtils.equals(response.body().getCode(), "200")) {
                        VerifyEventCommentBean.VerifyEventCommentData Data = response.body().getData();
                        if (Data != null && Data.Rows != null) {
                            if (view != null) {
                                view.getCommentSuccess(Data.Rows, Data.TotalNum);
                            }
                        } else {
                            if (view != null) {
                                view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                            }
                        }
                    } else {
                        if (view != null) {
                            view.fail(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<VerifyEventCommentBean> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                if (view != null) {
                    view.fail("请求失败，请重试");
                }
            }
        });
    }

    @Override
    public void download(int type, String fileUrl, String fileName) {
        Call<ResponseBody> call = model.downloadFile(fileUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        LogUtils.v("gogogo download file result = " + response.message() + "  length  " + response.body().contentLength() + "  type " + response.body().contentType());
                        if (response.body().contentLength() <= 0) {
                            if (view != null) {
                                view.fail("附件下载失败，请检查附件地址是否正确");
                            }
                            return;
                        }
                        ToastUtils.show("正在下载附件");
                        //建立一个文件
                        file = AttachmentHelper.createFile(fileName);
                        //下载文件放在子线程
                        downloadThread = new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                //保存到本地
                                AttachmentHelper.writeFile2Disk(response, file, new ForestCampTaskVerifyEventContract.FileDownloadCallBack() {
                                    @Override
                                    public void onLoading(final long current, final long total) {
                                        if (current >= total) {
                                            if (file != null) {
                                                if (view != null) {
                                                    view.downloadSuccess(type, file.getAbsolutePath());
                                                }
                                            }
                                        }
                                    }
                                });

                            }
                        };
                        downloadThread.start();

                    } else {
                        if (view != null) {
                            view.fail("请求失败，请重试");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                if (view != null) {
                    view.fail("请求失败，请重试");
                }
            }
        });
    }

    //中断下载线程
    private void stopDownloadFile() {
        if (downloadThread != null && !downloadThread.isInterrupted()) {
            downloadThread.interrupt();
        }
    }

    @Override
    public void destroy() {
        stopDownloadFile();
        view = null;
    }

}
